import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class AnimatedTextField extends StatefulWidget {
  // 输入框的控制器，用于获取和设置输入框的值
  // 例：final controller = TextEditingController();
  final TextEditingController controller;

  // 输入框的提示文本
  // 例："请输入用户名"
  final String hintText;

  // 输入框左侧的图标
  // 例：Icon(Icons.person) 或 LoadSvgWidget(R.icAccount)
  final Widget? prefixIcon;

  // 输入框右侧的图标
  // 例：Icon(Icons.visibility) 用于密码显示/隐藏
  final Widget? suffixIcon;

  // 是否隐藏输入内容，用于密码框
  // 例：true 显示为密码，false 显示为普通文本
  final bool obscureText;

  // 键盘类型
  // 例：TextInputType.number 数字键盘
  // TextInputType.phone 电话键盘
  // TextInputType.emailAddress 邮箱键盘
  final TextInputType keyboardType;

  // 输入验证函数，返回null表示验证通过，返回String表示错误信息
  // 例：(value) => value?.isEmpty ?? true ? '不能为空' : null
  final String? Function(String?)? validator;

  // 输入内容改变时的回调函数
  // 例：(value) => print('新输入的值：$value')
  final Function(String)? onChanged;

  // 点击输入框时的回调函数
  // 例：() => print('输入框被点击')
  final Function()? onTap;

  // 是否启用输入框
  // 例：false 表示输入框禁用状态
  final bool enabled;

  // 最大输入长度
  // 例：11 表示最多输入11个字符
  final int? maxLength;

  // 输入框宽度
  // 例：300.w
  final double? width;

  // 输入框高度
  // 例：50.h
  final double? height;

  // 未获取焦点时下划线颜色
  // 例：Colors.blue[600]
  final Color enabledLineColor;

  // 获取焦点时下划线颜色
  // 例：Colors.amber
  final Color focusedLineColor;

  // 光标颜色
  // 例：Colors.blue
  final Color? cursorColor;

  // 输入文字大小
  // 例：14 表示14sp
  final double fontSize;

  // 输入文字颜色
  // 例：Colors.black
  final Color textColor;

  // 提示文字颜色
  // 例：Colors.grey[400]
  final Color hintTextColor;

  // 输入文字样式
  // 例：TextStyle(fontWeight: FontWeight.bold)
  final TextStyle? textStyle;

  // 提示文字样式
  // 例：TextStyle(fontStyle: FontStyle.italic)
  final TextStyle? hintStyle;

  // 内容内边距
  // 例：EdgeInsets.symmetric(horizontal: 20.w)
  final EdgeInsetsGeometry? contentPadding;

  // 动画持续时间
  // 例：Duration(milliseconds: 300)
  final Duration animationDuration;

  // 图标大小约束
  // 例：BoxConstraints(minWidth: 40.w, minHeight: 20.h)
  final BoxConstraints? iconConstraints;

  // 普通状态下划线高度
  // 例：1.0 表示1像素
  final double lineHeight;

  // 获取焦点时下划线高度
  // 例：2.0 表示2像素
  final double focusedLineHeight;

  const AnimatedTextField({
    super.key,
    required this.controller,
    required this.hintText,
    this.prefixIcon,
    this.suffixIcon,
    this.obscureText = false,
    this.keyboardType = TextInputType.text,
    this.validator,
    this.onChanged,
    this.onTap,
    this.enabled = true,
    this.maxLength,
    this.width,
    this.height,
    this.enabledLineColor = Colors.black,
    this.focusedLineColor = Colors.black,
    this.cursorColor,
    this.fontSize = 14,
    this.textColor = Colors.black,
    this.hintTextColor = const Color(0xFF9E9E9E),
    this.textStyle,
    this.hintStyle,
    this.contentPadding,
    this.animationDuration = const Duration(milliseconds: 300),
    this.iconConstraints,
    this.lineHeight = 1.0,
    this.focusedLineHeight = 2.0,
  });

  @override
  State<AnimatedTextField> createState() => _AnimatedTextFieldState();
}

class _AnimatedTextFieldState extends State<AnimatedTextField>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<Color?> _borderColorAnimation;
  late Animation<double> _borderWidthAnimation;
  final FocusNode _focusNode = FocusNode();
  bool _hasError = false;

  @override
  void initState() {
    super.initState();
    _initializeAnimations();
    _setupFocusListener();
  }

  void _initializeAnimations() {
    _animationController = AnimationController(
      duration: widget.animationDuration,
      vsync: this,
    );

    _borderColorAnimation = ColorTween(
      begin: widget.enabledLineColor,
      end: widget.focusedLineColor,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));

    _borderWidthAnimation = Tween<double>(
      begin: widget.lineHeight,
      end: widget.focusedLineHeight,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
  }

  void _setupFocusListener() {
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        _animationController.forward();
      } else {
        _animationController.reverse();
        // 在失去焦点时验证输入
        if (widget.validator != null) {
          setState(() {
            _hasError = widget.validator!(widget.controller.text) != null;
          });
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      height: widget.height,
      margin: EdgeInsets.symmetric(vertical: 8.h),
      child: AnimatedBuilder(
        animation: _animationController,
        builder: (context, child) {
          return TextField(
            controller: widget.controller,
            focusNode: _focusNode,
            obscureText: widget.obscureText,
            keyboardType: widget.keyboardType,
            enabled: widget.enabled,
            maxLength: widget.maxLength,
            style: widget.textStyle ??
                TextStyle(
                  fontSize: widget.fontSize.sp,
                  color: widget.textColor,
                ),
            cursorColor: widget.cursorColor ?? widget.focusedLineColor,
            cursorHeight: (widget.fontSize + 2).sp,
            onChanged: (value) {
              if (widget.onChanged != null) {
                widget.onChanged!(value);
              }
              if (widget.validator != null) {
                setState(() {
                  _hasError = widget.validator!(value) != null;
                });
              }
            },
            onTap: widget.onTap,
            // 修改 build 方法中 TextField 的 decoration 部分
            decoration: InputDecoration(
              hintText: widget.hintText,
              hintStyle: widget.hintStyle ??
                  TextStyle(
                    fontSize: widget.fontSize.sp,
                    color: widget.hintTextColor,
                  ),
              prefixIcon: widget.prefixIcon != null
                  ? Padding(
                      padding: EdgeInsets.symmetric(horizontal: 12.w),
                      child: widget.prefixIcon,
                    )
                  : null,
              suffixIcon: widget.suffixIcon != null
                  ? Padding(
                      padding: EdgeInsets.symmetric(horizontal: 12.w),
                      child: widget.suffixIcon,
                    )
                  : null,
              counter: null,
              border: UnderlineInputBorder(
                borderSide: BorderSide(
                  color: _hasError ? Colors.red : _borderColorAnimation.value!,
                  width: _borderWidthAnimation.value.w,
                ),
              ),
              enabledBorder: UnderlineInputBorder(
                borderSide: BorderSide(
                  color: _hasError ? Colors.red : widget.enabledLineColor,
                  width: widget.lineHeight.w,
                ),
              ),
              focusedBorder: UnderlineInputBorder(
                borderSide: BorderSide(
                  color: _hasError ? Colors.red : _borderColorAnimation.value!,
                  width: _borderWidthAnimation.value.w,
                ),
              ),
              errorBorder: UnderlineInputBorder(
                borderSide: BorderSide(
                  color: Colors.red,
                  width: widget.lineHeight.w,
                ),
              ),
              contentPadding: widget.contentPadding ??
                  EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              prefixIconConstraints: widget.iconConstraints ??
                  BoxConstraints(
                    minWidth: 48.w,
                    minHeight: widget.fontSize * 2.5.sp,
                  ),
              suffixIconConstraints: widget.iconConstraints ??
                  BoxConstraints(
                    minWidth: 48.w,
                    minHeight: widget.fontSize * 2.5.sp,
                  ),
              isDense: true,
              floatingLabelBehavior: FloatingLabelBehavior.never,
              isCollapsed: false, // 改为 false
            ),
          );
        },
      ),
    );
  }

  @override
  void dispose() {
    _focusNode.dispose();
    _animationController.dispose();
    super.dispose();
  }
}
